package com.example.music.ui;

import androidx.appcompat.app.AppCompatActivity;
import androidx.room.Room;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import com.example.music.databinding.ActivityLoginBinding;
import com.example.music.room.AppDatabase;
import com.example.music.room.User;
import com.example.music.utlis.ToastUtil;


public class LoginActivity extends AppCompatActivity {

    ActivityLoginBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityLoginBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        binding.tvLoginLogin.setOnClickListener(v -> {
            login();
        });
        binding.tvLoginRegister.setOnClickListener(v -> {
            startActivity(new Intent(getBaseContext(),RegisterActivity.class));
        });
    }

    private void login(){
        String name = binding.editTextTextPersonName.getText().toString().trim();
        String password = binding.editTextTextPassword.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            ToastUtil.showShort(getBaseContext(),"账号不能为空");
            return;
        }
        if (TextUtils.isEmpty(password)) {
            ToastUtil.showShort(getBaseContext(),"密码不能为空");
            return;
        }
        AppDatabase db = Room.databaseBuilder(getBaseContext(), AppDatabase.class, "database-name").build();
        new Thread(new Runnable() {
            @Override
            public void run() {
                User loginUser = db.userDao().findByName(name, password);
                if(loginUser==null){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showShort(getBaseContext(),"账号/密码错误");
                        }
                    });
                    return;
                }
                loginUser.setOnline(true);
                db.userDao().updateUser(loginUser);
                finish();
            }
        }).start();
    }
}